package cn.com.shaom.learning.sb.shiro.example.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.net.UnknownHostException;

/**
 * ClassName: RedisConfig
 * Description: Redis 配置
 * Date: 2018/1/16 20:50 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Configuration
@AutoConfigureAfter(value = {RedisAutoConfiguration.class})
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        RedisJsonSerializer serializer = new RedisJsonSerializer();
        template.setKeySerializer(serializer);
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(serializer);
        template.setHashValueSerializer(serializer);
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }


    /**
     * ClassName: RedisJsonSerializer
     * Description: Redis 自定义序列化
     * Date: 2018/1/16 20:50 【需求编号】
     *
     * @author Sam Sho
     * @version V1.0.0
     */
    public static class RedisJsonSerializer implements RedisSerializer<Object> {
        public RedisJsonSerializer() {
        }

        @Override
        public byte[] serialize(Object o) throws SerializationException {
            return null == o ? new byte[0] : JSON.toJSONBytes(o, new SerializerFeature[]{SerializerFeature.WriteClassName});
        }

        @Override
        public Object deserialize(byte[] bytes) throws SerializationException {
            return null != bytes && bytes.length > 0 ? JSON.parse(bytes, new Feature[0]) : null;
        }
    }
}
